package com.zbp.service.impl;

import cn.hutool.json.JSONUtil;
import com.zbp.model.vo.LoginVO;
import com.zbp.model.vo.UserVO;
import com.zbp.service.LoginService;
import com.zbp.utils.RedisUtil;
import com.zbp.utils.jwt.JwtUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Objects;

/**
 * @author niuben
 */
@Service
public class LoginServiceImpl implements LoginService {

    @Resource
    private AuthenticationManager authenticationManager;

    @Autowired
    private RedisUtil redisUtil;

    @Override
    public LoginVO login(LoginVO loginVO) {
        //进行用户认证
        UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(loginVO.getUserName(), loginVO.getPassWord());
        Authentication authenticate = authenticationManager.authenticate(authenticationToken);
        //认证未通过，给出提示
        if (Objects.isNull(authenticate)) {
            throw new RuntimeException("登陆失败！");
        }
        UserVO userVO = (UserVO) authenticate.getPrincipal();
        //通过了，生成jwt
        loginVO.setPassWord(null);
        loginVO.setToken(JwtUtil.createJWT(JSONUtil.toJsonStr(authenticate.getPrincipal())));
        redisUtil.set("auth:" + loginVO.getToken(), JSONUtil.parse(loginVO).toString(), 60 * 60 * 1000L);
        return loginVO;
    }
}



